﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AdministracionAreasComunesWeb.Models;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;

namespace AdministracionAreasComunesWeb.Controllers
{
    public class ReservaController : Controller
    {
        private List<Reserva> CrearListaReservas()
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:23000/ReservaService.svc/Reservas");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string reservaJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<Reserva> reservaObtenida = js.Deserialize<List<Reserva>>(reservaJson);

            List<Reserva> reservas = new List<Reserva>();
            foreach (Reserva prop in reservaObtenida)
            {
                reservas.Add(new Reserva()
                {
                    Llave = Convert.ToInt32(prop.Llave),
                    Torre = Convert.ToInt32(prop.Torre),
                    Dpto = Convert.ToInt32(prop.Dpto),
                    Propietario = prop.Propietario,
                    IdAreaComun = Convert.ToInt32(prop.IdAreaComun),
                    DesAreaComun = prop.DesAreaComun,
                    HoraInicio = Convert.ToInt32(prop.HoraInicio),
                    HoraFin = Convert.ToInt32(prop.HoraFin),
                    Estado = prop.Estado
                });
            }
            return reservas;
        }
        
        private Reserva ObtenerReserva(int llave)
        {
            List<Reserva> reservas = (List<Reserva>)Session["reservas"];
            Reserva model = reservas.Single(delegate(Reserva reserva)
            {
                if (reserva.Llave == llave) return true;
                else return false;
            });
            return model;
        }

        //
        // GET: /Reserva/
        public ActionResult Index()
        {
            if (Session["reservas"] == null)
                Session["reservas"] = CrearListaReservas();
            List<Reserva> model = (List<Reserva>)Session["reservas"];
            return View(model);
        }

        //
        // GET: /Reserva/Create
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Reserva/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                int llave = int.Parse(collection["Torre"]) * 1000000 + int.Parse(collection["Dpto"]) * 1000 + int.Parse(collection["IdAreaComun"]) * 100 + int.Parse(collection["HoraInicio"]);
                string postdata = "{\"Llave\":" + llave.ToString() + ",\"Torre\":" + collection["Torre"] + ",\"Dpto\":" + collection["Dpto"] +
                    ",\"Propietario\":\"" + collection["Propietario"] +
                "\",\"IdAreaComun\":" + collection["IdAreaComun"] + ",\"DesAreaComun\":\"" + collection["DesAreaComun"] +
                    "\",\"HoraInicio\":" + collection["HoraInicio"] + ",\"HoraFin\":0,\"Estado\":\"\"}";
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest
                    .Create("http://localhost:23000/ReservaService.svc/Reservas");
                req.Method = "POST";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string reservaJson = reader.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                string msjResultado = js.Deserialize<string>(reservaJson);

                if (msjResultado.Equals(""))
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData["MsjError"] = "--- ERROR! " + msjResultado;
                    return View();
                }
            }
            catch (Exception e)
            {
                ViewData["MsjError"] = "--- ERROR! Datos incompatibles ---";
                return View();
            }
        }

        //
        // GET: /Reserva/Cancel/5 
        public ActionResult Cancelar(int id)
        {
            Reserva model = ObtenerReserva(id);
            return View(model);
        }

        //
        // POST: /Reserva/Cancelar/5

        [HttpPost]
        public ActionResult Cancelar(int id, FormCollection collection)
        {
            try
            {
                string ruta = "http://localhost:23000/ReservaService.svc/Reservas/" + id.ToString();
                HttpWebRequest req = (HttpWebRequest)WebRequest
                    .Create(ruta);
                req.Method = "DELETE";
                var res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string reservaJson = reader.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                string msjResultado = js.Deserialize<string>(reservaJson);

                if (msjResultado.Equals(""))
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData["MsjError"] = "--- ERROR! " + msjResultado;
                    return View();
                }
            }
            catch
            {
                ViewData["MsjError"] = "--- ERROR! ";
                return View();
            }
        }

        //
        // GET: /Reserva/Actualizar
        public ActionResult Actualizar()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Actualizar(FormCollection collection)
        {
            try
            {
                string ruta = "http://localhost:23000/ReservaService.svc/Reservas";
                HttpWebRequest req = (HttpWebRequest)WebRequest
                    .Create(ruta);
                req.Method = "PUT";
                var res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string reservaJson = reader.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                string msjResultado = js.Deserialize<string>(reservaJson);
            }
            catch
            {
                ViewData["MsjError"] = "--- ERROR! ";
                return View();
            }
            Session["reservas"] = CrearListaReservas();
            List<Reserva> model = (List<Reserva>)Session["reservas"];
            return View();
        }
    }
}
